package pl.un4giv3n.mightvsmagic.action.clan;

import java.io.File;

import javax.persistence.EntityManager;

import org.apache.commons.io.FileUtils;

import pl.un4giv3n.mightvsmagic.utils.FileExtensions;
import pl.un4giv3n.mightvsmagic.utils.ImageUtil;

/**
 * @author andrzejewskia
 * uploads user avatar
 */
public class UploadClanImageAction extends ClanAction {
	private static final long serialVersionUID = 1L;
	private File upload;// The actual file
	private String uploadContentType; // The content type of the file
	private String uploadFileName; // The uploaded file name
	private String fileCaption;// The caption of the file entered by user

	public String execute() {
		EntityManager entityManager = getEntityManager();
		user = getSessionUser(entityManager);
		if (user == null) {
			entityManager.close();
			return LOGIN;
		}
		clan = user.getClan();
		if(clan == null || !isCanConfigClan()){
			entityManager.close();
			addActionError("Brak klanu lub niewystarczające uprawnienia!");
			return ERROR;
		}
		entityManager.close();
		try {
			//first delete the old avatar
			for (FileExtensions ext : FileExtensions.values()) {
				String pathname = getContext().getRealPath("/")+ImageUtil.EXT_CLAN_IMG_BASE_DIR+clan.getId()+"."+ext.getExt();
				File filepath = new File(pathname);
				if(filepath.exists()){
					filepath.delete();
				}
			}
			//create the new file
			String fullFileName = getContext().getRealPath("/")
					+ ImageUtil.EXT_CLAN_IMG_BASE_DIR;
			File theFile = new File(fullFileName);
			if (!theFile.exists()) {
				theFile.mkdirs();
			}
			int mid= uploadFileName.lastIndexOf(".");
		    String ext=uploadFileName.substring(mid+1,uploadFileName.length());
			fullFileName = fullFileName + clan.getId() + "."+FileExtensions.valueOf(ext.toUpperCase()).getExt();
			theFile = new File(fullFileName);
			if (!theFile.exists()) {
				theFile.createNewFile();
			}
			//copy the uploaded content to the new file
			FileUtils.copyFile(upload, theFile);

		} catch (Exception e) {

			e.printStackTrace();
			addActionError(e.getMessage());

			return ERROR;

		}
		return SUCCESS;

	}
	
	public String getFileCaption() {
		return fileCaption;
	}

	public void setFileCaption(String fileCaption) {
		this.fileCaption = fileCaption;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
}
